package com.xxx.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.pojo.Employee;
import com.xxx.service.EmployeeService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService service;

    @RequiresRoles(value = {"admin","manage","employee"},logical = Logical.OR)
    @GetMapping("/page")
    public Result getByPage(int page,int pageSize,String name){
        IPage iPage = new Page(page,pageSize);

        iPage = service.getByPage(iPage, name);



        Result r = new Result(iPage,Code.GET_OK);

        return r;
    }

    @RequiresRoles(value = {"admin","manage"},logical = Logical.OR)
    @PostMapping
    public Result save(@RequestBody Employee employee){

        employee.setPassword(BCrypt.hashpw(employee.getPassword(),BCrypt.gensalt()));

        int save = service.save(employee);
        Result r = new Result();
        if (save >0){
            r.setCode(Code.SAVE_OK);
            r.setMessage("添加成功");
        }else {
            r.setCode(Code.SAVE_ERR);
            r.setMessage("404 系统出错");
        }
        return r;
    }



    @RequiresRoles(value = {"admin","manage"},logical = Logical.OR)
    @PutMapping
    public Result modifyStatus(HttpServletRequest request, @RequestBody Employee employee){
//        HttpSession session = request.getSession();
//        Long employeeId = (Long) session.getAttribute("employeeId");
//        LocalDateTime dateTime = LocalDateTime.now();
//
//        employee.setUpdateUser(employeeId);
//        employee.setUpdateTime(dateTime);
//        System.out.println(employee);


        Result r = new Result();
        int i = service.modifyStatus(employee);
        if (i>0){
            r.setCode(Code.UPDATE_OK);
            r.setData(employee);
        }else {
            r.setCode(Code.UPDATE_ERR);
            r.setMessage("404 失败");
        }
        return r;
    }
}
